#include<stdio.h>
#include<stdlib.h>
struct ListNode
{
    int val;
    struct ListNode* next;
};
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
    if (list1 == NULL)
        return list2;
    if (list2 == NULL)
        return list1;

    struct ListNode* tail = NULL, * newhead = NULL;
    while (list1 && list2)
    {
        if (list1->val > list2->val)
        {
            if (newhead == NULL)
            {
                tail = newhead = list2;
            }
            else
            {
                tail->next = list2;
                tail = tail->next;
            }
            list2 = list2->next;
        }
        else
        {
            if (newhead == NULL)
            {
                tail = newhead = list1;
            }
            else
            {
                tail->next = list1;
                tail = tail->next;
            }
            list1 = list1->next;
        }
    }
    if (list1)
    {
        tail->next = list1;
        tail = tail->next;
    }
    if (list2)
    {
        tail->next = list2;
        tail = tail->next;
    }
    return newhead;
}
void ListNodePrint(struct ListNode* phead)
{
    struct ListNode* cur = phead;
    while (cur)
    {
        printf("%d->", cur->val);
        cur = cur->next;
    }
    printf("\n");
}
int main()
{
    struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    n1->val = 1;
    n2->val = 2;
    n3->val = 3;
    n4->val = 5;
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = NULL;
    ListNodePrint(n1);
    struct ListNode* n5 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n6 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n7 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n8 = (struct ListNode*)malloc(sizeof(struct ListNode));
    n5->val = 2;
    n6->val = 3;
    n7->val = 4;
    n8->val = 9;
    n5->next = n6;
    n6->next = n7;
    n7->next = n8;
    n8->next = NULL;
    ListNodePrint(n5);
    
    ListNodePrint(mergeTwoLists(n1, n5));

    return 0;
}